<?php

class AdminCategoriesController extends AdminController {

    public function index() {
        $this->set('categories', CategoryModel::tree());
    }

    public function add($parentId=null) {
        if ($parentId) {
            $this->set('parent', CategoryModel::get($parentId));
        }

        $this->render('form', false);
    }

    public function edit($id) {
        $category = CategoryModel::get($id);
        $this->set('category', $category);

        $this->render('form', false);
    }

    public function remove($id) {
        $hash = '';
        if (CategoryModel::delete(array('id' => $id))) {
            $this->flash('Kategorija je obrisana.', 'ok');
        } else {
            $hash = "#!/admin_categories/edit/{$id}";
            $this->flash('Kategorija nije obrisana.');
        }
        $this->redirect("/admin_categories/{$hash}");
    }

    public function save() {
        $category_hash = '';
        $data = $this->POST('data');
        if ($data) {
            $id = (int)$data['id'];

            if ($id>0) {
                $saved = CategoryModel::update($data, array('id' => $id));
            } else {
                unset($data['id']);
                $saved = CategoryModel::insert($data);
                $id = CategoryModel::lastInsertId();
            }


            $category_hash = "#!/admin_categories/edit/{$id}";
            
            if ($saved) {
                $this->flash('Kategorija je sačuvana', 'ok');
            } else {
                $this->flash('Kategorija nije sačuvana');
            }

        }
        $this->redirect("/admin_categories/{$category_hash}");
    }

    public function resort() {
        $this->autoRender = false;
        $data = $this->POST('order');
        if ($data) {
            foreach ($data as $id => $order) {
                CategoryModel::update(array(
                    'order' => $order
                ), array( 'id' => $id));
            }
        }
        echo 'reordered';
    }

    public function reorder($id, $parentId) {
        $this->autoRender = false;
        $parentId = (int)$parentId;
        if (! $parentId) {
            $parentId = null;
        }

        $updated = CategoryModel::update(array(
            'parent_id' => $parentId
        ), array( 'id' => $id));

        echo $updated ? 'Reordered' : 'Failed ' . CategoryModel::sql();
    }

}